package com.example.hotel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class home extends Activity implements OnClickListener {
	
	int num = 0;
	String msg = "";
	final Context context = this;
	Dialog show_message;
	TextView message;
	 Runnable Refresh;
	Integer a = 0;
	Integer b = 1;
	Integer c = 2;
	Integer tx1 = 0;
	Integer tx2 = 1;
	Integer tx3 = 2;
	int indext = 3;
	int i = 0;
	int i0 = 0;
	int i1 = 1;
	int i2 = 2;
	int j1 = 1;
	int j2 = 2;
	int j3 = 3;
	Integer item = 0;
	Integer item1 = 0;
	String[] menu = null;
	String wellcome1 ="";
	Button bt_left, bt_right;
TextView tv_txt1, tv_txt2, tv_txt3, tv_menu,wellcome,tvAmount;
ImageView imv_img1, imv_img2, imv_img3,image_cart,image_mgs, image_bill;
	Integer[] Image = { R.drawable.hotel, R.drawable.tv_channels,
			R.drawable.services, R.drawable.localattraction, R.drawable.games,
			R.drawable.movies, R.drawable.social, R.drawable.offices_tools,
			/*R.drawable.inroomshopping,*/ R.drawable.browser };

	String nameMenu = "";
	String message_new = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);

		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		wellcome = (TextView)findViewById(R.id.tvWellcome);
		getMenu();
		getNameCustomer();
		((Global)getApplicationContext()).callpage1 = com.example.hotel.home.class;
		bt_left = (Button) findViewById(R.id.left);
		bt_right = (Button) findViewById(R.id.right);
		imv_img1 = (ImageView) findViewById(R.id.image1);
		imv_img2 = (ImageView) findViewById(R.id.image2);
		imv_img3 = (ImageView) findViewById(R.id.image3);
		image_cart = (ImageView) findViewById(R.id.image_cart);
		 image_mgs = (ImageView)findViewById(R.id.image_msg);
		image_bill = (ImageView)findViewById(R.id.image_bill);
		tv_txt1 = (TextView) findViewById(R.id.tv1);
		tv_txt2 = (TextView) findViewById(R.id.tv2);
		tv_txt3 = (TextView) findViewById(R.id.tv3);
		tvAmount = (TextView)findViewById(R.id.tvAmount);
		tv_menu = (TextView) findViewById(R.id.tvMenu);
		bt_left.setOnClickListener(this);
		bt_right.setOnClickListener(this);
		imv_img1.setOnClickListener(this);
		imv_img2.setOnClickListener(this);
		imv_img3.setOnClickListener(this);
		image_cart.setOnClickListener(this);
		image_bill.setOnClickListener(this);
		image_mgs.setOnClickListener(this);
		item = Image.length % 3;
		item1 = Image.length - item;
		String str = "";
		
		imv_img1.setImageResource(Image[a]);
		imv_img2.setImageResource(Image[b]);
		imv_img3.setImageResource(Image[c]);		
		tv_txt1.setText(menu[j1]);
		tv_txt2.setText(menu[j2]);
		tv_txt3.setText(menu[j3]);
		tv_menu.setText(menu[0]);
		tvAmount.setText("("+((Global)getApplicationContext()).cart_count.toString()+")");

		String lang = ((Global) getApplicationContext()).lang;
		String imie = ((Global) getApplicationContext()).imei;
		final String url = ((Global) getApplicationContext()).url1;
		final List<NameValuePair> params = new ArrayList<NameValuePair>();
		message_new = getMessege(str);
		 if (message_new.equals("")) {

		} else {
			final Handler handler = new Handler();
			  Refresh  = new Runnable() {
				public void run() {
					String str= "";
					message_new = getMessege(str);
					 if (message_new.equals("")) {
						 
					 }
					 else
					 {
							msbox(message_new);
					 }					
					handler.postDelayed(this, 5000);
				}
			};
			//handler.post(Refresh);
			/*show_message = new Dialog(context);
			show_message.setContentView(R.layout.show_message);
			show_message.setTitle("Message For Your");
			message = (TextView) show_message.findViewById(R.id.message);
			message.setText(Html.fromHtml(str));
			show_message.show();*/

		}

		 
		/*params.add(new BasicNameValuePair("strLang", lang));
		params.add(new BasicNameValuePair("strImie", imie));
		String resultServer = getHttpPost(url, params);
		try {
			JSONObject data = new JSONObject(resultServer);
			msg = data.getString("content");
			num = data.getInt("pkid");
		} catch (JSONException e) {
			e.printStackTrace();
		}*/
		/*Refresh = new Runnable() {
			public void run() {
				int id;
				String resultServer = getHttpPost(url, params);
				try {
					JSONObject data = new JSONObject(resultServer);
					msg = data.getString("content");
					id = data.getInt("pkid");
					if (id > num) {
						num = id;
						msbox(msg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				handler.postDelayed(Refresh, 5000);
			}
		};
		handler.post(Refresh);*/

		/*------setfonts------*/
		Typeface Font = Typeface.createFromAsset(getAssets(),
				"fonts/PSL-Kittithada.ttf");
		Typeface FontBold = Typeface.createFromAsset(getAssets(),
				"fonts/PSL-KittithadaBold.ttf");
		TextView tv_amount = (TextView) findViewById(R.id.tvAmount);
		tv_txt1.setTypeface(Font);
		tv_txt2.setTypeface(Font);
		tv_txt3.setTypeface(Font);
		tv_amount.setTypeface(Font);
		tv_menu.setTypeface(FontBold);
		
		/*--------------------*/
		((Global)getApplicationContext()).callpage_bool = false;
		((Global) getApplicationContext()).Switch_page = false;
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.right:

			if (item == 1 && i + 3 == item1) {

				i += 3;
				i0 += 3;
				i1 += 3;
				i2 += 3;
				j1 += 3;
				j2 += 3;
				j3 += 3;
				imv_img1.setImageResource(Image[i]);
				imv_img2.setImageResource(0);
				imv_img3.setEnabled(false);
				imv_img3.setImageResource(0);
				imv_img3.setEnabled(false);
				tv_txt1.setText(menu[j1]);
				tv_txt2.setText(" ");
				tv_txt3.setText(" ");

			} else if (item == 2 && i + 3 == item1) {
				i += 3;
				i0 += 3;
				i1 += 3;
				i2 += 3;
				j1 += 3;
				j2 += 3;
				j3 += 3;
				imv_img1.setImageResource(Image[i]);
				imv_img2.setImageResource(Image[i + 1]);
				imv_img3.setImageResource(0);
				imv_img3.setEnabled(false);
				tv_txt1.setText(menu[j1]);
				tv_txt2.setText(menu[j2]);
				tv_txt3.setText("");

			} else if (i2 + 3 < Image.length) {

				i += 3;
				i0 += 3;
				i1 += 3;
				i2 += 3;
				j1 += 3;
				j2 += 3;
				j3 += 3;
				indext++;
				a = Image[i0];
				b = Image[i1];
				c = Image[i2];
				imv_img1.setImageResource(a);
				imv_img2.setImageResource(b);
				imv_img3.setImageResource(c);
				imv_img1.setEnabled(true);
				imv_img2.setEnabled(true);
				imv_img3.setEnabled(true);
				tv_txt1.setText(menu[j1]);
				tv_txt2.setText(menu[j2]);
				tv_txt3.setText(menu[j3]);
			}

			break;
		case R.id.left:

			if (i > 0 && i0 < Image.length) {
				i -= 3;
				i0 -= 3;
				i1 -= 3;
				i2 -= 3;
				j1 -= 3;
				j2 -= 3;
				j3 -= 3;
				c = Image[i2];
				b = Image[i1];
				a = Image[i0];
				imv_img1.setImageResource(a);
				imv_img2.setImageResource(b);
				imv_img3.setImageResource(c);
				imv_img1.setEnabled(true);
				imv_img2.setEnabled(true);
				imv_img3.setEnabled(true);
				tv_txt1.setText(menu[j1]);
				tv_txt2.setText(menu[j2]);
				tv_txt3.setText(menu[j3]);
			}
			break;
		case R.id.image1:
			((Global)getApplicationContext()).callpage_bool = true;
			switch (i0) {			
			case 0:
				((Global) getApplicationContext()).nameMenu = menu[i0 + 1];	
				startActivity(new Intent(home.this, Hotel_info.class));
				break;
			case 3:
				((Global) getApplicationContext()).nameMenu = menu[i0 + 1];				
				startActivity(new Intent(home.this, Local_attraction.class));
				break;
			case 6:
				((Global) getApplicationContext()).nameMenu = menu[i0 + 1];
				startActivity(new Intent(home.this, Social.class));
				break;
		/*	case 9:
				try{
				PackageManager manager = getPackageManager();
                Intent is = new Intent(Intent.ACTION_MAIN);
                is= manager.getLaunchIntentForPackage("com.android.browser");
                startActivity(is);
				}catch (Exception e) {
					Toast.makeText(context, "Application not found", Toast.LENGTH_LONG).show();
				}
				break;*/
			}
			break;
		case R.id.image2:
			((Global)getApplicationContext()).callpage_bool = true;
			switch (i1) {
			case 1:
				try{
				PackageManager manager = getPackageManager();
                Intent is = new Intent(Intent.ACTION_MAIN);
                is= manager.getLaunchIntentForPackage("com.amlogic.DVBPlayer");
                startActivity(is);
				}catch (Exception e) {
					Toast.makeText(context, "Application not found", Toast.LENGTH_LONG).show();
				}
				break;
			case 4:
				((Global) getApplicationContext()).nameMenu = menu[i1 + 1];
				startActivity(new Intent(home.this, Games.class));
				break;
			case 7:
				((Global) getApplicationContext()).nameMenu = menu[i1 + 1];
				startActivity(new Intent(home.this, Office_tool.class));
				break;
			}
			break;
		case R.id.image3:
			((Global)getApplicationContext()).callpage_bool = true;
			switch (i2) {
			case 2:
				((Global) getApplicationContext()).nameMenu = menu[i2 + 1];
				startActivity(new Intent(home.this, Service.class));
				break;
			case 5:
				try{
				PackageManager manager = getPackageManager();
                Intent is = new Intent(Intent.ACTION_MAIN);
                is= manager.getLaunchIntentForPackage("com.example.hotelmovie");
                startActivity(is);
				}catch (Exception e) {
					Toast.makeText(context, "Application not found", Toast.LENGTH_LONG).show();
				}
				break;
			case 8:
				try{
					PackageManager manager = getPackageManager();
	                Intent is = new Intent(Intent.ACTION_MAIN);
	                is= manager.getLaunchIntentForPackage("com.android.browser");
	                startActivity(is);
					}catch (Exception e) {
						Toast.makeText(context, "Application not found", Toast.LENGTH_LONG).show();
					}
				break;
			/*	((Global) getApplicationContext()).nameMenu = menu[i2 + 1];
				startActivity(new Intent(home.this, Room_shopping.class));
				break;*/
			}
			break;
		case R.id.image_cart:
			((Global) getApplicationContext()).nameCart = "show_cart";
			startActivity(new Intent(home.this, Add_cart.class));
			break;
		case R.id.image_msg:
			startActivity(new Intent(home.this, Message_list.class));

			break;
		case R.id.image_bill:
			startActivity(new Intent(home.this, Billing_history.class));
			break;
		}
		
			
		

	}


	public String getMessege(String srt) {
		String URL1 = ((Global) getApplicationContext()).url;
		String SOAP_ACTION = ((Global) getApplicationContext()).soap_acction + "message";
		String NAMESPACE = "";
		String METHOD_NAME = "message";
		String imei = ((Global) getApplicationContext()).imei;
		String lang = ((Global) getApplicationContext()).lang;
		String str = "";
		String message = "";
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapObject responses = null;
		request.addProperty("id", imei);
		request.addProperty("lang", lang);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
		androidHttpTransport.debug = true;

		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			responses = (SoapObject) envelope.bodyIn;
			str = responses.toString();
			int indexSub = str.indexOf("=");
			String b = str.substring(indexSub + 1);
			indexSub = b.indexOf(";");
			b = b.substring(0, indexSub);
			String[] a = b.split("\\|");
			if (a[0].equals("1")) {

				message = a[1];
			} else {
				message = a[1];
			}

		} catch (Exception e) {
		
		}
		return message;
	}

	public void getNameCustomer() {
		String URL1 = ((Global) getApplicationContext()).url;
		String SOAP_ACTION = ((Global) getApplicationContext()).soap_acction + "home";
		String NAMESPACE = "";
		String METHOD_NAME = "home";
		String lang = ((Global) getApplicationContext()).lang;
		String device_id = ((Global) getApplicationContext()).imei;
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapObject responses = null;
		request.addProperty("id", device_id);
		request.addProperty("lang", lang);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
		androidHttpTransport.debug = true;

		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			responses = (SoapObject) envelope.bodyIn;
			String str = responses.toString();
			int indexSub = str.indexOf("=");
			String b = str.substring(indexSub + 1);
			indexSub = b.indexOf(";");
			b = b.substring(0, indexSub);
			String[] a = b.split("\\|");
			TextView tv_wellcome = (TextView) findViewById(R.id.tvWellcome);
			tv_wellcome.setText(a[0] + " : " + a[1]);
			Typeface ThaiFont = Typeface.createFromAsset(getAssets(),
					"fonts/PSL-KittithadaBold.ttf");
			tv_wellcome.setTypeface(ThaiFont);
			((Global) getApplicationContext()).wellcome = a[0] + " : " + a[1];
		} catch (Exception e) {
			AlertDialog.Builder builder = new AlertDialog.Builder(home.this);
	    	builder.setTitle("Alert Dailog")
	    	.setIcon(getResources().getDrawable(R.drawable.logo))
	    	.setMessage("Not connect internet")
	    	.setPositiveButton("Close", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(home.this, MainActivity.class));
				}
			});
	    	AlertDialog alert = builder.create();
	    	alert.show();
		}
	}
	public void getMenu() {
		String URL1 = ((Global) getApplicationContext()).url;
		String SOAP_ACTION = ((Global) getApplicationContext()).soap_acction + "menu";
		String NAMESPACE = "";
		String METHOD_NAME = "menu";
		String lang = ((Global) getApplicationContext()).lang;
		String device_id = ((Global) getApplicationContext()).imei;
		// ((Global)getApplicationContext()).imei = device_id;
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		SoapObject responses = null;
		request.addProperty("id", device_id);
		request.addProperty("lang", lang);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL1);
		androidHttpTransport.debug = true;

		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			responses = (SoapObject) envelope.bodyIn;
			String str = responses.toString();
			int indexSub = str.indexOf("=");
			String b = str.substring(indexSub + 1);
			indexSub = b.indexOf(";");
			b = b.substring(0, indexSub);
			menu = b.split("\\|");

		} catch (Exception e) {
			AlertDialog.Builder builder = new AlertDialog.Builder(home.this);
	    	builder.setTitle("Alert Dailog")
	    	.setIcon(getResources().getDrawable(R.drawable.logo))
	    	.setMessage("Not connect internet")
	    	.setPositiveButton("Close", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(home.this, MainActivity.class));
				}
			});
	    	AlertDialog alert = builder.create();
	    	alert.show();
		}
	}

	public String getHttpPost(String url, List<NameValuePair> params) {
		StringBuilder str = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response = client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) { // Status OK
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
			} else {
				Log.e("Log", "Failed to download result..");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str.toString();
	}

	public void msbox(String str) {
		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setTitle("Message to you");
		dlgAlert.setIcon(getResources().getDrawable(R.drawable.icon_massege));
		dlgAlert.setMessage(str);
		dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {				
				
			}
		});
		dlgAlert.setCancelable(true);
		MediaPlayer mMedia = MediaPlayer.create(this, R.raw.music);
		mMedia.start();
		dlgAlert.create().show();
	}

}
